package com.example.usercenter.rocketmq;

import com.example.usercenter.dao.bonus_event_log.BonusEventLogMapper;
import com.example.usercenter.dao.user.UserMapper;
import com.example.usercenter.domain.entity.bonus_event_log.BonusEventLog;
import com.example.usercenter.domain.entity.user.User;
import com.example.usercenter.domain.messaging.UserAddBonusMsgDTO;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName: AddBonusListener
 * @Author: lerry_li
 * @CreateDate: 2021/06/10
 * @Description
 */
@Service
@RocketMQMessageListener(consumerGroup = "consumer-group", topic = "add-bonus")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AddBonusListener implements RocketMQListener<UserAddBonusMsgDTO> {
    private final UserMapper userMapper;
    private final BonusEventLogMapper bonusEventLogMapper;

    @Override
    public void onMessage(UserAddBonusMsgDTO message) {
        //当受到消息的时候，执行的业务
        //1. 为用户加积分
        Integer userId = message.getUserId();
        User user = this.userMapper.selectByPrimaryKey(userId);
        Integer bonus = message.getBonus();
        user.setBonus(user.getBonus() + bonus);
        this.userMapper.updateByPrimaryKey(user);
        //2.记录日志到bonus_event_log表里
        this.bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(userId)
                        .value(bonus)
                        .event("CONTRIBUTE")
                        .createTime(new Date())
                        .description("投稿加积分")
                        .build()
        );
    }
}
